package net.linku.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 字段自动填充
 */
@Component
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject, "createdBy", Long.class, userId);
        this.strictInsertFill(metaObject, "lastUpdatedBy", Long.class, userId);
        this.strictInsertFill(metaObject, "creationDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "lastUpdateDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "enabledFlag", Integer.class, 1);
        this.strictInsertFill(metaObject, "deletedFlag", Integer.class, 0);
        this.strictInsertFill(metaObject, "objectVersionNumber", Long.class, 1L);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictUpdateFill(metaObject, "lastUpdatedBy", Long.class, userId);
        this.strictUpdateFill(metaObject, "lastUpdateDate", Date.class, new Date());
    }

    private Long getUserId() {
        Long userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            String principal = authentication.getPrincipal().toString();
            if ("anonymousUser".equals(principal)) {
                userId = -1L;
            } else {
                userId = Long.valueOf(principal);
            }
        }
        return userId;
    }
}
